package com.fintech.pangu.oauth2.config.token;

import com.fintech.pangu.oauth2.properties.OAuth2AuthorizationServerProperties;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.security.oauth2.provider.token.store.redis.RedisTokenStore;

/**
 * Redis TokenStore配置
 */
@Configuration
@ConditionalOnClass(RedisConnectionFactory.class)
public class RedisTokenStoreConfig {

    @Autowired
    private RedisConnectionFactory redisConnectionFactory;

    @Autowired
    private OAuth2AuthorizationServerProperties oAuth2AuthorizationServerProperties;

    @Value("${spring.application.name}")
    private String defaultTokenPrefix;

    /**
     * Token存储的前缀
     * 如果没有配置pangu.oauth2.server.tokenStore.prefix的话，默认取spring.application.name
     * @return
     */
    private String getTokenPrefix() {
        String configuredPrefix = oAuth2AuthorizationServerProperties.getTokenStore().getPrefix();
        if(StringUtils.isEmpty(configuredPrefix)){
            return defaultTokenPrefix;
        }
        else{
            return configuredPrefix;
        }
    }

    /**
     * Redis存储令牌
     * @return
     */
    @Bean
    public TokenStore redisTokenStore(){
        RedisTokenStore redisTokenStore = new RedisTokenStore(redisConnectionFactory);
        redisTokenStore.setPrefix(getTokenPrefix() + ":");
        return redisTokenStore;
    }

}
